import {
  defineConfig
} from 'vite';
import vue from '@vitejs/plugin-vue';
import path from 'path';

import dotenv from 'dotenv';

export default ({
  mode
}) => {
  const fs = require('fs');
  try {
    // 根据环境变量加载环境变量文件
    const file = dotenv.parse(fs.readFileSync(`.env.${mode}`));
    // 根据获取的key给对应的环境变量赋值
    for (const key in file) {
      process.env[key] = file[key];
    }
  } catch (e) {
    console.error(e);
  }
  console.log('当前环境:',process.env.VITE_TITLE);
  return defineConfig({
    base: './',
    //定义主题色
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `$sub-color: #7096f9;`
        },
        less: {
          modifyVars: {
            'primary-color': '#7096f9',
          },
          javascriptEnabled: true,
        }
      },
    },
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src')
      },
      extensions: ['.js', '.vue', '.json', '.scss', '*']
    },
    build: {
      outDir: 'dist',
      // outDir: process.env.VITE_ENV,
      rollupOptions: {
        output: {
          manualChunks: {
            vlib: ['vue', 'vue-router', 'vuex']
          }
        }
      }
    },
    server: {
      host: '0.0.0.0',
      port: 8088,
      open: false,
      cors: process.env.VITE_ENV == 'dev' ? true : false,
      proxy: {
        '/wms': {
          target: process.env.VITE_BASE_URL + '/wms',
          changeOrigin: true,
          rewrite: path => path.replace(/^\/wms/, '')
        },
      }
    },
    plugins: [
      vue()
    ],
  })
}